package com.cet.spring_batch_study.jobs.xmlReader;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.xml.StaxEventItemReader;
import org.springframework.batch.item.xml.builder.StaxEventItemReaderBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.xstream.XStreamMarshaller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionManager;

import java.math.BigDecimal;
import java.util.HashMap;

/**
 * @author NSOC
 */
@Configuration
public class XmlReaderConfig {

    @Bean
    public Job xmlParseJob(JobRepository jobRepository,
                           Step ingestingXmlAndDisplay) {
        return new JobBuilder("xmlParseJob", jobRepository)
                .start(ingestingXmlAndDisplay)
                .build();
    }

    @Bean
    public Step ingestingXmlAndDisplay(JobRepository jobRepository,
                                       PlatformTransactionManager transactionManager,
                                       ItemReader<Trade> xmlItemReader,
                                       ItemWriter<Trade> displayTradeWriter) {
        return new StepBuilder("ingestingXmlAndDisplayStep",jobRepository)
                .<Trade, Trade> chunk(5, transactionManager)
                .reader(xmlItemReader)
                .writer(displayTradeWriter)
                .build();


    }

    @Bean
    public StaxEventItemReader<Trade> xmlItemReader(XStreamMarshaller tradeMarshaller) {
        return new StaxEventItemReaderBuilder<Trade>()
                .name("xmlItemReader")
                .resource(new ClassPathResource("trades.xml"))
                .addFragmentRootElements("trade")
                .unmarshaller(tradeMarshaller)
                .build();
    }

    @Bean
    public XStreamMarshaller tradeMarshaller() {
        HashMap<String, Class<?>> aliases = new HashMap<>();
        aliases.put("trade", Trade.class);
        aliases.put("price", BigDecimal.class);
        aliases.put("isin", String.class);
        aliases.put("customer", String.class);
        aliases.put("quantity", Long.class);

        XStreamMarshaller marshaller = new XStreamMarshaller();
        marshaller.setAliases(aliases);
        marshaller.getXStream().allowTypes(new Class[]{Trade.class});
        return marshaller;
    }


}
